package com.huage_10.lesson_02;

import java.lang.reflect.Field;

/*
        反射获取成员变量并使用
 */
public class ReflectDemo02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        //获取Class对象
        Class<?> c = Class.forName("com.huage_10.lesson_02.Student");

        //获取成员变量
        System.out.println("获取公有成员变量");
        Field[] fields1 = c.getFields();
        for (Field field : fields1){
            System.out.println(field);
        }
        System.out.println("--------");

        System.out.println("获取所有成员变量");
        Field[] fields2 = c.getDeclaredFields();
        for (Field field : fields2){
            System.out.println(field);
        }
        System.out.println("--------");

        //创建实例并给成员变量赋值
        Object obj = c.newInstance();
        Field address = c.getField("address");
        address.set(obj,"北京");
        System.out.println(obj);
        System.out.println("--------");

        Field name = c.getDeclaredField("name");
        //暴力反射
        name.setAccessible(true);
        name.set(obj,"北京");
        System.out.println(obj);
        System.out.println("--------");

    }
}
